const express = require('express')
const router = express.Router()
const path = require('path')
const fs = require('fs')
const multer = require('multer')
const moment = require('moment')
const UserModel = require(path.join(process.cwd(), '/models/UserModel'))
const RoleModel = require(path.join(process.cwd(), '/models/RoleModel'))
const md5 = require('md5')
const jwt = require('jsonwebtoken')
const { secret } = require(path.join(process.cwd(), '/config/config'))
const checkTokenMiddleware = require(path.join(process.cwd(), '/middlewares/checkTokenMiddleware'))

// 设置 multer 存储
const storage = multer.memoryStorage()
const upload = multer({ storage: storage })

// 登录用户
router.post('/user/login', async (req, res) => {
  const { username, password } = req.body
  try {
    const hasUser = await UserModel.findOne({ username: username }, { new: true })
    if (!hasUser) return res.sendResult(null, 200, 'User not registered')
    const data = await UserModel.findOne({ username: username, password: md5(password) })
    if (!data) return res.sendResult(null, 200, 'Password error')
    if (data.state === 0) return res.sendResult(null, 200, 'Disabled user')
    const token = jwt.sign(
      {
        iat: Math.floor(Date.now() / 1000)
      },
      secret,
      { expiresIn: 60 * 60 * 24 }
    )
    const resData = {
      _id: data._id,
      username: username,
      rid: data.role_id,
      token: token,
      createTime: data.create_time
    }
    return res.sendResult(resData, 200, '登录成功')
  } catch (error) {
    return res.sendResult(error.message, 400, '登录失败')
  }
})

// 新增用户
router.post('/user/register', upload.single('file'), async (req, res) => {
  const { username, password } = req.body
  try {
    const hasUser = await UserModel.findOne({ username: username }, { new: true })
    if (hasUser) return res.sendResult(null, 200, 'User exists')
    let avatarBuffer, contentType
    if (req.file) {
      avatarBuffer = req.file.buffer
      contentType = req.file.mimetype
    } else {
      const defaultAvatarPath = path.join(process.cwd(), 'public/images/defaultAvatar.jpg')
      avatarBuffer = fs.readFileSync(defaultAvatarPath)
      contentType = 'image/jpeg'
    }
    const data = await UserModel.create({
      username: username,
      password: md5(password),
      avatar: avatarBuffer,
      contentType: contentType,
      create_time: moment(req.body.time).toDate()
    })
    return res.sendResult(data._id, 200, '创建成功')
  } catch (error) {
    return res.sendResult(error.message, 400, '请求失败')
  }
})

// 修改用户跟密码
router.put('/user/:uId', checkTokenMiddleware, async (req, res) => {
  const { password } = req.body
  try {
    const data = await UserModel.findByIdAndUpdate(req.params.uId, { password: md5(password) }, { new: true })
    if (data) return res.sendResult({ userID: data._id }, 200, '修改密码成功')
    return res.sendResult(null, 404, '用户未找到')
  } catch (error) {
    return res.sendResult(error.message, 400, '请求失败')
  }
})

// 修改用户状态
router.put('/user/:uId/state/:state', checkTokenMiddleware, async (req, res) => {
  const { uId, state } = req.params
  try {
    const data = await UserModel.findByIdAndUpdate(uId, { state: Number(state) }, { new: true })
    if (data) return res.sendResult({ userID: data._id }, 200, '修改状态成功')
    return res.sendResult(null, 404, '用户未找到')
  } catch (error) {
    return res.sendResult(error.message, 400, '请求失败')
  }
})

// 获取用户总数
router.get('/users/totalCount', checkTokenMiddleware, async (req, res) => {
  try {
    const total = await UserModel.countDocuments() // 获取总记录数
    return res.sendResult(total, 200, '用户总数成功')
  } catch (error) {
    return res.sendResult(error.message, 400, '获取失败')
  }
})

// 分页查询用户
router.get('/user', checkTokenMiddleware, async (req, res) => {
  const page = parseInt(req.query.page) || 1 // 当前页数，默认为1
  const limit = parseInt(req.query.limit) || 10 // 每页条数，默认为10
  try {
    const data = await UserModel.find()
      .sort({ create_time: 1 })
      .skip((page - 1) * limit) // 跳过前面已获取的数据
      .limit(limit) // 限制每页的数据量

    const total = await UserModel.countDocuments() // 获取总记录数
    // 遍历 `data` 数组，构建响应数据
    const itemData = await Promise.all(
      data.map(async (user) => {
        const role = await RoleModel.findOne({ role_id: user.role_id })
        return {
          _id: user._id,
          role_id: user.role_id,
          avatarPath: `/avatar/${user._id}`,
          username: user.username,
          state: user.state,
          role_name: role ? role.role_name : null, // 确保 role 存在
          create_time: user.create_time
        }
      })
    )
    return res.sendResult(
      {
        isPagination: true,
        itemData,
        total,
        page,
        totalPages: Math.ceil(total / limit) // 总页数
      },
      200,
      '获取用户列表成功'
    )
  } catch (error) {
    console.log(error)
    return res.sendResult(error.message, 400, '获取失败')
  }
})

// 根据 ID 查询用户信息
router.get('/users/:uId', checkTokenMiddleware, async (req, res) => {
  try {
    const data = await UserModel.findById(req.params.uId)
    const { password, ...resData } = data.toObject()
    return res.sendResult(resData, 200, '获取用户信息成功')
  } catch (error) {
    return res.sendResult(error.message, 400, '获取失败')
  }
})

// 删除单个用户
router.delete('/user/:uId', checkTokenMiddleware, async (req, res) => {
  try {
    const data = await UserModel.findById(req.params.uId)
    if (!data) return res.sendResult(null, 404, '用户未找到')
    await UserModel.deleteOne({ _id: req.params.uId })
    return res.sendResult({ userID: data._id }, 200, '删除用户成功')
  } catch (error) {
    return res.sendResult(error.message, 400, '请求失败')
  }
})

// 修改用户角色
router.put('/user/:uId/role/:rId', checkTokenMiddleware, async (req, res) => {
  const { uId, rId } = req.params
  try {
    const data = await UserModel.findByIdAndUpdate(uId, { role_id: rId }, { new: true })
    if (data) return res.sendResult({ userID: data._id }, 200, '修改状态成功')
    return res.sendResult(null, 404, '用户未找到')
  } catch (error) {
    return res.sendResult(error.message, 400, '请求失败')
  }
})

// 根据角色 ID 获取角色信息
router.get('/role/:rId', checkTokenMiddleware, async (req, res) => {
  try {
    const data = await RoleModel.findOne({ role_id: req.params.rId })
    if (data) {
      const resData = {
        _id: data._id,
        role_id: data.role_id,
        role_name: data.role_name,
        role_desc: data.role_desc
      }
      return res.sendResult(resData, 200, '获取角色信息成功')
    }
    return res.sendResult(null, 404, '角色信息未找到')
  } catch (error) {
    return res.sendResult(error.message, 400, '获取失败')
  }
})

// 根据用户名和角色名称模糊查询用户
router.post('/user/search', checkTokenMiddleware, async (req, res) => {
  const { username, role_name } = req.body
  // 构建查询条件
  const query = {}
  if (username) query.username = { $regex: username, $options: 'i' }
  if (role_name) {
    const roleData = await RoleModel.find({ role_name: { $regex: role_name, $options: 'i' } })
    if (roleData && roleData.length > 0) query.role_id = { $in: roleData.map((role) => role.role_id) } // 提取 role_id
  }
  try {
    const data = await UserModel.find(query)
    // 遍历 `data` 数组，构建响应数据
    const itemData = await Promise.all(
      data.map(async (user) => {
        const role = await RoleModel.findOne({ role_id: user.role_id })
        return {
          _id: user._id,
          role_id: user.role_id,
          avatarPath: `/avatar/${user._id}`,
          username: user.username,
          state: user.state,
          role_name: role ? role.role_name : null, // 确保 role 存在
          create_time: user.create_time
        }
      })
    )
    return res.sendResult(
      {
        isPagination: false,
        itemData
      },
      200,
      '查询用户列表成功'
    )
  } catch (error) {
    return res.sendResult(error.message, 400, '请求失败')
  }
})

module.exports = router
